package network;

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import icu.ac.kr.phonebook.activity.SeachScheduleActivity;
import icu.ac.kr.phonebook.activity.SecretDiaryMain;
import icu.ac.kr.phonebook.provider.ConstantProvider;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

public class NetworkModule {

	Handler handler;
	Context ctx;
	ProgressDialog progress;
	static final String TAG = "NetworkModule";
	static int number;
	static String ip;
	static String method;
	static String remoteIp;

	ServerSocket serverSocket;
	
    public static String getLocalIpAddress(){
    	
    	
    	try {
			for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();en.hasMoreElements();)
			{
				
				NetworkInterface nif = en.nextElement();
				
				for (Enumeration<InetAddress> inets= nif.getInetAddresses(); inets.hasMoreElements();)
				{
					InetAddress inetAddress = inets.nextElement();
					if (!inetAddress.isLoopbackAddress())
						return "192.168.1.5"; //
						
			//			return inetAddress.getHostAddress().toString();
					
				}
				
			}
		
    	} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	
    	return ip;
    }

	
	public NetworkModule(SeachScheduleActivity seachScheduleActivity,
			Handler handler) {
		// TODO Auto-generated constructor stub
	
		ctx = seachScheduleActivity;
		this.handler = handler;
		
	}

	
	public NetworkModule(SecretDiaryMain secretDiaryMain) {
		// TODO Auto-generated constructor stub
		ctx = secretDiaryMain;
	}


	public void connectToServer(int number2, String ip2, String method2){

		number = number2;
		ip = ip2; 
		method = method2;
 		
		Thread thread = new Thread(){
			
			public void run(){

				try {
					URL url = new URL("http://192.168.1.6:8080/RestfulServer/number/"+number+"/ip/"+ip+"/");
					
					HttpURLConnection  con = (HttpURLConnection ) url.openConnection();
					con.setRequestMethod(method);
					 
					BufferedReader reader = new BufferedReader(new InputStreamReader (con.getInputStream()));
					
					StringBuilder line = new StringBuilder();
					String temp = null;  
 					 
 					while(true)
					{
					
						 temp = reader.readLine(); 
						 
						 if (temp == null) break;
						line.append(temp);
					
						
					}
  
 				Log.d(TAG, line.toString());
 			 	JSONObject object = (JSONObject) new JSONTokener(line.toString()).nextValue();
 				JSONObject object2 = object.getJSONObject("report");
 				
 				
 				Log.d(TAG, "IP : "+ object2.getString("ip") + " Number: " + object2.getInt("number"));
 				remoteIp = object2.getString("ip");
 				
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		
		};
		
		thread.run();
		
	}
	
	
	public String getRemoteIp(){
		return remoteIp;
	}
	
 
	public String connectToTerminal(String date, String month, String year, String terminalIp) {
		// TODO Auto-generated method stub

		StringBuilder builder = new StringBuilder();
	  	   
		// connect to Terminal
		
		// run the Dialog View of SearchActivity 
			try{
				
				Socket socket = new Socket(terminalIp, 9997);
				Log.d(TAG, "IP:" + socket.getInetAddress().getHostAddress()
		    	       + ", port:" + socket.getPort());
		    	   
		  	   
		  	   OutputStream toServer = socket.getOutputStream();
		  	   InputStream fromServer = socket.getInputStream();
		  	   System.out.println("Connected...");
		  	   
		  	   JSONObject request = new JSONObject();
		  	   ArrayList<Integer> v1 = new ArrayList<Integer>();
		  	   v1.add(Integer.parseInt(year));
		  	   v1.add(Integer.parseInt(month));
		  	   v1.add(Integer.parseInt(date));
		  	   request.put("date", v1);
		  	    
			   Log.d(TAG, request.toString());
		  	   
		  	   toServer.write(request.toString().getBytes());
		  	   toServer.write("bye".getBytes());
		  	   toServer.flush();
		  	   
		  	   byte[] by = new byte[1024];
		  	   int read = 0;
		  	   
		  	   while(true)
		  	   {
		  		 read = fromServer.read(by);
		  		 if (read < 0) break;
		  		 //Log.d(TAG, new String(by));
		  		 builder.append(new String(by));
		  		 
		  	   }
		  	   Log.d(TAG, builder.toString());
		  	   
		  	   toServer.close();
		  	   System.out.println("Done...");
		  	  }
		  	  catch (Exception ex) {
		  	   System.err.println(ex.getMessage());
		  	  }
	
		  	  return builder.toString();
		
		
	}

	public void stopServer(){
		
		try {
			serverSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public void runServer() {
		// TODO Auto-generated method stub
	
		Log.d(TAG, "Server is running");
		Thread thread = new Thread(){
			
			public void run(){
				
				try {
					Log.d(TAG, "@@@@@@@@@@@@@@@ 1" );
				        
					serverSocket = new ServerSocket(9997);
					Log.d(TAG, "@@@@@@@@@@@@@@@ 2" );
			        
					while(true)
					{
						Log.d(TAG, "@@@@@@@@@@@@@@@ 3" );
				        
					Socket socket = serverSocket.accept();
					Log.d(TAG, "@@@@@@@@@@@@@@@ 4" );
			        
					new ClientHandler(socket).start();
				
					}
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		};
		
		thread.start();
		Log.d(TAG, "Server is started");	
	}
	
	
	private class ClientHandler extends Thread{

		Socket socket;
		
		
		
		public ClientHandler(Socket socket)
		{
			this.socket = socket;
			
		}
		
		public void run() {
			// TODO Auto-generated method stub
		
		// communicate with clients	
	           InputStream input;
	           OutputStream output;
	           try {
				input = socket.getInputStream();
				output = socket.getOutputStream();

	           byte[] by = new byte[1024];
	           StringBuilder builder = new StringBuilder();
	    	   Log.d(TAG, "################### 1" );
	        	       
	           while(true)
	           {
	        	 
	        	   	input.read(by);
	        	      
	        	   	
	        	   	String str = new String(by);
	        	    builder.append(str); 
	        	   	
	        	    if (str.contains("bye"))
	        	    	break;
	        	    Log.d(TAG, str );
    	          
	           }

	           Log.d(TAG, "################### 2" );
	        	 
	           JSONObject obj = (JSONObject) new JSONTokener(builder.toString()).nextValue();
	           JSONArray obj2 = new JSONArray(obj.getString("date"));
	           
	           Cursor cursor = ctx.getContentResolver().query(ConstantProvider.TOTALSCHEDULE_URI, new String[]{"hour", "type", "comment","mode"}, "year ="+ obj2.getInt(0) +" and month ="+obj2.getInt(1) +" and date="+obj2.getInt(2), null, "hour desc");
	           JSONObject scheduleObj = new JSONObject();
	           
	           JSONArray array = new JSONArray();
	           while(cursor.moveToNext())
	           {
	        	
	        	
	        	  JSONObject row =  new JSONObject();
	        	  row.put("hour", ""+cursor.getInt(cursor.getColumnIndex(ConstantProvider.diary.HOUR)));
	        	  row.put("type", ""+cursor.getString(cursor.getColumnIndex(ConstantProvider.diary.TYPE)));
	        	  row.put("comment", ""+cursor.getString(cursor.getColumnIndex(ConstantProvider.diary.COMMENT)));
	        	  row.put("mode", ""+cursor.getInt(cursor.getColumnIndex(ConstantProvider.diary.MODE)));
	        	  array.put(row);
	        	  
	           }
	           cursor.close();
	           Log.d(TAG, array.toString());
	           
	           output.write(array.toString().getBytes());
	           
	           Log.d(TAG, "Communicating with client is completed");
			
	           socket.close();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		
	}
	
	
}
